<template>
	<!-- 资产盘点（详情） -->
	<view class="my-apply">
		<!-- <view class="top-head" :style="{height:`${44+safeTop}px`,paddingTop:`${safeTop}px`}">
			<text class="iconfont icon-left-arrow" @click="goBack"></text>
			<text class="title">盘点详情</text>
			<text
				@click="toJump(`/pages/checkAssets/addAsset/index?checkStoreId=${checkStoreId}&version=${version}`)" v-if="mainInfo.status!==8" class="iconfont icon-xinzeng"></text>
				<text v-else></text>
		</view> -->
		<picker :range="pickerRange" @change="bindPickerChange" :disabled="pickerDisabled">
			<view class="tab-posi">
				<NewSegmentedControl :current="current" :values="items" style-type="text" active-color="#198a6c"
					@clickItem="onClickItem" />
			</view>
		</picker>
		<view class="content">
			<view class="card">
				<view class="head">
					<text>{{mainInfo.assetCheckName||'--'}}</text>
					<text
						:class="{checking:mainInfo.status==7,haveinventory:mainInfo.status==8}">{{mainInfo.statusCh}}</text>
				</view>
				<view class="list">
					<view>盘点编号：{{mainInfo.assetCheckNo||'--'}}</view>
					<view>盘点单位：{{mainInfo.storeName}}</view>
					<view>盘点人：{{mainInfo.checkerCh||'--'}}</view>
					<view>盘点期限：{{mainInfo.assetCheckExpectDate?.replace('T',' ')||'--'}}</view>
					<view class="remark">备注信息：{{mainInfo.remarks||'--'}}</view>
				</view>
			</view>
			<view class="card all-num">
				<view>
					<text>{{mainInfo.ckAssetTotalNum}}</text>
					<text>资产总数</text>
				</view>
				<view>
					<text>{{mainInfo.inventoryOkNum}}</text>
					<text>已盘点数</text>
				</view>
				<view>
					<text>{{mainInfo.inventoryNgNum}}</text>
					<text>盘亏数</text>
				</view>
				<view>
					<text>{{mainInfo.inventoryExtraNum}}</text>
					<text>盘盈数</text>
				</view>
			</view>
			<view class="card" v-for="item in myApplyList" :key="item.assetCheckDtlId">
				<view class="head">
					<text>{{item.assetName}}({{item.assetNo}})</text>
					<text
						:class="{inventory:item.status===4,'color-pu-bg':item.status===2,'color-r-bg':item.status===3}">{{item.statusCh}}</text>
				</view>
				<view class="list">
					<view>盘点人：{{item.checkerCh||'--'}}</view>
					<view>盘点方式：{{item.checkTypeCh||'--'}}</view>
					<view>盘点时间：{{item.checkTime?.replace('T',' ')||'--'}}</view>
					<view class="btn" v-if="mainInfo.status!==8">
						<button v-if="item.status===4" @click="delAsset(item)">删除</button>
						<radio-group @change="radioChange($event,item)" v-show="item.status!==4">
							<label class="radio">
								<radio value="1" :checked="item.status==1?true:false" />未盘点
							</label>
							<label class="radio">
								<radio value="2" :checked="item.status==2?true:false" />盘点存在
							</label>
							<label class="radio">
								<radio value="3" :checked="item.status==3?true:false" />盘点不存在
							</label>
						</radio-group>
					</view>
				</view>
			</view>
			<!-- 加载结束 -->
			<view class="uni-loadmore" v-if="showLoadMore" style="margin-bottom: 88rpx;">{{loadMoreText}}</view>
		</view>

		<view class="bottom-btn" v-if="mainInfo.status!==8">
			<button type="default" @click="endCheckBtn">
				结束盘点
			</button>
			<button type="default" @click="saveResult">保存结果</button>
			<button type="default" @click="
          toJump(
            `/pages/qrCode/qrCode?tip=结束扫码盘点&successUrl=/pages/checkAssets/checkResult/index&clickTipUrl=/pages/checkAssets/checkResult/index`
          )
        ">
				扫码盘点
			</button>
		</view>
		<MessageTip ref="messageTip" :tipContent="'确认删除吗？'" @clickType="handleShowOrHideTip" />
	</view>
</template>

<script setup lang="ts">
	import {
		ref,

	} from "vue";
	import {
		onLoad,
		onNavigationBarButtonTap,
		onPullDownRefresh,
		onShow,
		onBackPress,

	} from "@dcloudio/uni-app";
	import {
		assetCheckSubList,
		getAllEnum,
		updateAssetCheck,
		checkStoreInfo,
		assetNameList,
		endCheck,
		delDtl
	} from "@/common/api/assetCheckAPI.ts";
	import {
		applyPerson
	} from "@/common/api/myApply";
	import {
		CONSTANT
	} from "@/common/config/config.ts";
	import {
		fromSearch
	} from "@/common/util/tabSearchUse.ts";
	const messageTip = ref()
	const current = ref(0);
	const items = ref(["盘点方式", "资产名称", "盘点人", "盘点状态"]);
	const pickerRange = ref();
	const pickerDisabled = ref(false);
	const currentTab = ref(0);
	const myApplyList = ref([]);
	const checkType = ref([])
	const person = ref([])
	const status = ref([])
	const assetName = ref([])
	const checkStoreId = ref()
	const version = ref()
	const exDeleteAssetCheckDtlIds = ref([])
	const mainInfo = ref( < any > {})
	const showLoadMore = ref(false);
	const loadMoreText = ref("加载中...");
	const searchParams = ref({
		checker: '',
		status: '',
		checkType: '',
		assetName: ''
	});
	const matchRule = {
		checker: 'eq',
		status: 'eq',
		checkType: 'eq',
		assetName: 'cn'
	};

	interface EnumType {
		label: string;
		value: string;
	}
	onBackPress((e) => {
		uni.navigateTo({
			url: '/pages/checkAssets/index'
		});
		return true;
	})
	onLoad((params) => {
		checkStoreId.value = params.checkStoreId
		version.value = params.version
		getMainList()
		getApplyList();
		getApplyAddr()

	});
	const pages = getCurrentPages()
	pages.forEach(item => {
		console.log('--------', item.route)
	})
	onNavigationBarButtonTap((e) => {
		if (mainInfo.value.status !== 8) {
			uni.navigateTo({
				url: `/pages/checkAssets/addAsset/index?checkStoreId=${checkStoreId.value}&version=${version.value}`
			})
		} else {
			uni.showToast({
				icon: "none",
				title: '此盘点状态不能新增资产！'
			})
		}

	})
	const getMainList = () => {
		checkStoreInfo(checkStoreId.value).then((res: any) => {
			if (res.code == 0) {
				mainInfo.value = res.data
				uni.setStorageSync('assetCheckName', mainInfo.value)
			}
		})
	}
	const getApplyList = () => {
		loadMoreText.value = '加载中...'
		assetCheckSubList(checkStoreId.value, {
			...fromSearch(searchParams.value, matchRule)
		}).then((res: any) => {
			uni.stopPullDownRefresh();
			if (res.code == 0) {
				uni.setStorageSync(
					'checkData',
					res.data
				);
				myApplyList.value = []
				setTimeout(() => {
					myApplyList.value = res.data
					if (myApplyList.value.length === 0) {
						showLoadMore.value = true;
						loadMoreText.value = "暂无数据";
					} else if (myApplyList.value.length < CONSTANT.pageSize) {
						showLoadMore.value = true;
						loadMoreText.value = "没有更多的数据了";
					} else {
						showLoadMore.value = false;
					}
				}, 0)


			} else {
				uni.showToast({
					icon: "none",
					title: res.message,
				});
			}
		})
	};
	onPullDownRefresh(() => {
		myApplyList.value = [];
		getApplyList();
	});
	const getApplyAddr = () => {
		assetNameList(checkStoreId.value).then((res: any) => {
			if (res.code == 0) {
				assetName.value = res.data
				assetName.value.push('全部')
			}
		})
		getAllEnum('*').then((res: any) => {
			if (res.code == 0) {
				status.value = res.data['AssetCheckDtlStatus'].map((item: any) => {
					return {
						label: item.value,
						value: item.code
					}
				})
				checkType.value = res.data['AssetCheckDtlCheckType'].map((item: any) => {
					return {
						label: item.value,
						value: item.code
					}
				})
			}
		})
		applyPerson().then((res: any) => {
			if (res.code == 0) {
				person.value = res.data.records.map((item: any) => {
					return {
						label: item.nickName,
						value: item.id
					}
				})
			}
		})
	}
	const onClickItem = (e: {
		currentIndex: number
	}) => {
		currentTab.value = e.currentIndex
		switch (e.currentIndex) {
			case 0:
				pickerRange.value = checkType.value.map((item: EnumType) => item.label);
				pickerRange.value.push('全部')
				break
			case 1:
				pickerRange.value = assetName.value;
				// pickerRange.value.push('全部')
				break
			case 2:
				pickerRange.value = person.value.map((item: EnumType) => item.label);
				pickerRange.value.push('全部')
				break
			case 3:
				pickerRange.value = status.value.map((item: EnumType) => item.label);
				pickerRange.value.push('全部')
				break
		}
	};
	const bindPickerChange = (e: any) => {
		let len = pickerRange.value.length - 1
		myApplyList.value = []
		switch (currentTab.value) {
			case 0:
				items.value[0] = e.detail.value == len ? '盘点方式' : pickerRange.value[e.detail.value];
				searchParams.value.checkType = e.detail.value == len ? '' : (checkType.value[e.detail
					.value] as EnumType).value;
				break
			case 1:
				items.value[1] = e.detail.value == len ? '资产名称' : pickerRange.value[e.detail.value];
				searchParams.value.assetName = e.detail.value == len ? '' : assetName.value[e.detail.value];
				break
			case 2:
				items.value[2] = e.detail.value == len ? '盘点人' : pickerRange.value[e.detail.value];
				searchParams.value.checker = e.detail.value == len ? '' : (person.value[e.detail.value] as EnumType)
					.value;
				break
			case 3:
				items.value[3] = e.detail.value == len ? '盘点状态' : pickerRange.value[e.detail.value];
				searchParams.value.status = e.detail.value == len ? '' : (status.value[e.detail.value] as EnumType)
					.value;
				break
		}
		getApplyList()
	};
	const toJump = (str: string) => {
		uni.setStorageSync('resultData', [])
		uni.redirectTo({
			url: str,
		});
		uni.setStorageSync('checkDetailParams', {
			checkStoreId: checkStoreId.value,
			version: version.value
		})
	};
	const saveResult = () => {
		let arr = []
		arr = myApplyList.value.filter((item: any) => item.changed == true)
		arr.forEach(item => {
			item.checkType = 2
		})
		updateAssetCheck({
			checkStoreId: checkStoreId.value,
			exDeleteAssetCheckDtlIds: exDeleteAssetCheckDtlIds.value,
			executeAssets: arr,
			version: mainInfo.value.version
		}).then((res: any) => {
			if (res.code == 0) {
				uni.showToast({
					title: res.message,
					icon: "none"
				})
				getMainList()
				getApplyList()
			}
		})
	}
	const radioChange = (e: any, obj: any) => {
		console.log('单选改变', e.detail.value, obj);
		myApplyList.value.forEach((item: any) => {
			if (item.assetCheckDtlId == obj.assetCheckDtlId) {
				item.changed = true
				item.status = e.detail.value / 1
				switch (e.detail.value / 1) {
					case 1:
						item.statusCh = '未盘点';
						break;
					case 2:
						item.statusCh = '盘点存在';
						break;
					case 3:
						item.statusCh = '盘点不存在';
						break;
				}
			}
		})
	}
	let opI = null
	const delAsset = (item: string) => {
		opI = item
		messageTip.value.openTip()
	}
	const handleShowOrHideTip = (type: string) => {
		if (type == 'yes') {
			console.log(opI)
			delDtl({
				exDeleteAssetCheckDtlIds: [opI.assetCheckDtlId],
				version: opI.version,
				checkStoreId: opI.checkStoreId
			}).then(res => {
				uni.showToast({
					title: res.message,
					icon: "none"
				})
				getApplyList()
				// 静态删除
				// myApplyList.value.forEach((item: any, index) => {
				// 	if (item.assetCheckDtlId === opI.checkStoreId) {
				// 		myApplyList.value.splice(index, 1)
				// 		exDeleteAssetCheckDtlIds.value.push(opI.checkStoreId);
				// 	}
				// })
			})
		}
	}
	const endCheckBtn = () => {
		endCheck([{
			checkStoreId: checkStoreId.value,
			version: version.value / 1
		}]).then((res: any) => {
			if (res.code == 0) {
				uni.showToast({
					title: res.message,
					icon: "none",
					duration: 500
				})
				setTimeout(() => {
					uni.navigateTo({
						url: `/pages/checkAssets/index`
					})
				}, 500)

			}
		})
	}
</script>

<style scoped lang="scss">
	.my-apply {
		position: relative;
		height: 100%;
		background-color: #eee;
		overflow: auto;
	}

	.card {
		&:last-child {
			margin-bottom: 100rpx;
		}

		.inventory {
			background-color: #fe9d01 !important;
		}

		:deep(.uni-radio-input) {
			width: 36rpx !important;
			height: 36rpx !important;
		}

		.list {
			padding-top: 20rpx;

			&>view {
				line-height: 1.5em;

				&:first-child {
					font-size: 14px;
					padding: 0;
				}
			}

			.btn {
				border-top: 1px solid #eee;
				padding-top: 18rpx;
				margin-top: 18rpx;

				&>uni-button {
					width: 25%;
					background-color: #008d6a;
					color: #fff;
					line-height: 1.8;
					margin-right: 0;
					font-size: 16px;
				}

				uni-radio-group {
					display: flex;
					justify-content: space-between;
				}
			}
		}
	}

	.all-num {
		display: flex;
		justify-content: space-around;

		&>view {
			display: flex;
			flex-direction: column;
			align-items: center;
			border-radius: 10rpx;
			padding: 20rpx;
			font-size: 14px;
			width: 152rpx;
			box-sizing: border-box;

			text {
				&:first-child {
					font-weight: 600;
				}
			}

			&:first-child {
				background-color: #fdf5e8;

				text {
					&:first-child {
						color: #fe9d01;
					}
				}
			}

			&:nth-child(2) {
				background-color: #e5f4ef;

				text {
					&:first-child {
						color: #008d6a;
					}
				}
			}

			&:nth-child(3) {
				background-color: #fff0f3;

				text {
					&:first-child {
						color: #f2959c;
					}
				}
			}

			&:last-child {
				background-color: #ecf2fe;

				text {
					&:first-child {
						color: #6998f4;
					}
				}
			}
		}
	}

	.bottom-btn {
		display: flex;

		// uni-button {
		// 	color: #fff;
		// 	border-radius: 46rpx;
		// 	font-size: 14px;
		// 	padding: 0 40rpx;

		// 	&:first-child {
		// 		background-color: #999999;
		// 	}

		// 	&:nth-child(2) {
		// 		background-color: #ff9d02;
		// 	}

		// 	&:last-child {
		// 		background-color: #008d6a;
		// 	}
		// }
		button {
			color: #fff;
			border-radius: 46rpx;
			font-size: 14px;
			padding: 0 40rpx;

			&:first-child {
				background-color: #999999;
			}

			&:nth-child(2) {
				background-color: #ff9d02;
			}

			&:last-child {
				background-color: #008d6a;
			}
		}
	}
</style>
